import React, { useState, useRef } from 'react';
import { View, Text, SafeAreaView, TextInput, TouchableOpacity, Image, Modal, ScrollView, Alert } from 'react-native';
import { Toast } from '@ant-design/react-native';
import Header from '../../../components/Header';
import CustomQRScanner from '../../../components/CustomQRScanner';
import { scanMesMBomMaterialClaimList, getShelfByShelfNum, claimMaterial } from './api';
import saoma from '../../../assets/saoma.png';
import { styles } from './styles';

interface PickingProps {
    onNavigateToLogin?: () => void;
    onBackPress?: () => void;
}

const Picking: React.FC<PickingProps> = ({ onNavigateToLogin, onBackPress }) => {
    const [workOrderNumber, setWorkOrderNumber] = useState('');
    const [shelfNumber, setShelfNumber] = useState('');
    const [workOrderScanVisible, setWorkOrderScanVisible] = useState(false);
    const [shelfScanVisible, setShelfScanVisible] = useState(false);
    const [loading, setLoading] = useState(false);
    const [materialList, setMaterialList] = useState<any[]>([]);
    const [workOrderData, setWorkOrderData] = useState<any>(null);
    const [selectedMaterials, setSelectedMaterials] = useState<any[]>([]);

    // 储位输入框的引用
    const shelfInputRef = useRef<TextInput>(null);

    // 扫描工单
    const handleWorkOrderScan = () => {
        setWorkOrderScanVisible(true);
    };

    // 扫描储位
    const handleShelfScan = () => {
        setShelfScanVisible(true);
    };

    // 处理工单扫描结果
    const handleWorkOrderScanResult = async (data: string) => {
        setWorkOrderScanVisible(false);
        setWorkOrderNumber(data);
        await handleWorkOrderSubmit(data);
    };

    // 处理储位扫描结果
    const handleShelfScanResult = async (data: string) => {
        setShelfScanVisible(false);
        // 处理二维码格式，获取#后面的内容
        const processedData = data.includes('#') ? data.split('#')[1] : data;
        setShelfNumber(processedData);
        await handleShelfSubmit(processedData);
        // 扫描完成后重置输入框，保持焦点状态
        setTimeout(() => {
            setShelfNumber('');
            // 重新聚焦到输入框
            shelfInputRef.current?.focus();
        }, 500);
    };

    // 提交工单
    const handleWorkOrderSubmit = async (value: string) => {
        if (!value.trim()) return;

        setLoading(true);
        try {
            const response = await scanMesMBomMaterialClaimList({ qr_code: value });
            console.log('工单扫描成功:', response);

            if (response.code === 200 && response.data) {
                setWorkOrderData(response.data);
                // 提取物料列表数据
                const materials = response.data.list || [];
                const allMaterials: any[] = [];

                materials.forEach((item: any) => {
                    if (item.material_list && Array.isArray(item.material_list)) {
                        item.material_list.forEach((material: any) => {
                            allMaterials.push({
                                ...material,
                                totalQuantity: item.quantity, // 总需求数量
                                materialName: item.material_name, // 物料名称
                                materialEncode: item.material_encode, // 物料编码
                            });
                        });
                    }
                });

                setMaterialList(allMaterials);
            }
        } catch (error) {
            console.error('工单扫描失败:', error);
            // 这里可以添加错误提示
        } finally {
            setLoading(false);
        }
    };

    // 提交储位
    const handleShelfSubmit = async (value: string) => {
        if (!value.trim()) return;

        setLoading(true);
        try {
            const response = await getShelfByShelfNum({ shelf_num: value });
            console.log('储位查询成功:', response);

            if (response.code === 200 && response.data) {
                // 检查是否已经选择过该储位的物料
                const existingIndex = selectedMaterials.findIndex(
                    item => item.shelf_num === response.data.shelf_num
                );

                if (existingIndex === -1) {
                    // 添加新物料到已选列表
                    const newMaterial = {
                        id: response.data.id,
                        product_name: response.data.product_name,
                        product_encode: response.data.product_encode,
                        product_id: response.data.product_id, // 添加product_id字段
                        material_id: response.data.material_id, // 添加material_id字段（如果有的话）
                        material_encode: response.data.material_encode, // 添加material_encode字段（如果有的话）
                        shelf_num: response.data.shelf_num,
                        quantity: response.data.quantity,
                        claimQuantity: '', // 领用数量输入框
                    };
                    setSelectedMaterials(prev => [...prev, newMaterial]);
                } else {
                    // 如果已存在，提示用户
                    Toast.info('该储位物料已选择', 1.5);
                }
            }
        } catch (error) {
            console.error('储位查询失败:', error);
            // 这里可以添加错误提示
        } finally {
            setLoading(false);
        }
    };

    // 工单输入框回车处理
    const handleWorkOrderSubmitEditing = () => {
        handleWorkOrderSubmit(workOrderNumber);
    };

    // 储位输入框回车处理
    const handleShelfSubmitEditing = () => {
        const currentValue = shelfNumber;
        handleShelfSubmit(currentValue);
        // 手动输入完成后也重置输入框，保持焦点状态
        setTimeout(() => {
            setShelfNumber('');
            // 重新聚焦到输入框
            shelfInputRef.current?.focus();
        }, 500);
    };

    // 更新领用数量
    const handleClaimQuantityChange = (index: number, value: string) => {
        setSelectedMaterials(prev =>
            prev.map((item, i) =>
                i === index ? { ...item, claimQuantity: value } : item
            )
        );
    };

    // 删除已选物料
    const handleDeleteMaterial = (index: number) => {
        Alert.alert(
            '确认删除',
            '确定要删除这个物料吗？',
            [
                { text: '取消', style: 'cancel' },
                {
                    text: '确定',
                    onPress: () => {
                        setSelectedMaterials(prev => prev.filter((_, i) => i !== index));
                    }
                }
            ]
        );
    };

    // 领料提交
    const handleClaimSubmit = async () => {
        if (selectedMaterials.length === 0) {
            Toast.info('请先选择要领用的物料', 1.5);
            return;
        }

        // 检查是否所有物料都填写了领用数量
        const invalidMaterials = selectedMaterials.filter(item => !item.claimQuantity || item.claimQuantity === '');
        if (invalidMaterials.length > 0) {
            Toast.info('请填写所有物料的领用数量', 1.5);
            return;
        }

        // 检查领用数量是否超过储位数量
        const overQuantityMaterials = selectedMaterials.filter(item =>
            parseInt(item.claimQuantity) > item.quantity
        );
        if (overQuantityMaterials.length > 0) {
            Toast.info('领用数量不能超过储位数量', 1.5);
            return;
        }

        setLoading(true);
        try {
            // 构建领料数据
            const claimData = selectedMaterials.map(material => ({
                shelf_num: material.shelf_num,
                quantity: parseInt(material.claimQuantity),
                product_id: material.product_id,
                material_id: material.material_id || material.product_id, // 储位查询接口没有material_id的话就用product_id
                product_encode: material.product_encode,
                material_encode: material.material_encode || material.product_encode, // 储位查询接口没有material_encode的话就用product_encode
                batch_order_num: workOrderData?.batch_order_num || '',
                mbom_num: workOrderData?.mbom_num || ''
            }));

            const response = await claimMaterial(claimData);

            if (response.code === 200) {
                Toast.success('领料成功', 1.5);
                // 清空已选物料列表
                setSelectedMaterials([]);
                // 清空工单数据
                setWorkOrderData(null);
                setMaterialList([]);
                setWorkOrderNumber('');
            } else {
                Toast.fail(response.msg || '领料失败', 1.5);
            }
        } catch (error) {
            console.error('领料失败:', error);
            Toast.fail('领料失败，请重试', 1.5);
        } finally {
            setLoading(false);
        }
    };

    return (
        <SafeAreaView style={styles.container}>
            <Header
                title="领料"
                showBackButton={true}
                onNavigateToLogin={onNavigateToLogin}
                onBackPress={onBackPress}
            />
            <View style={styles.content}>
                <ScrollView style={styles.scrollContent} showsVerticalScrollIndicator={false}>
                    {/* 工单扫描区域 */}
                    <View style={styles.scanSection}>
                        <Text style={styles.sectionTitle}>工单扫描</Text>
                        <View style={styles.inputRow}>
                            <View style={styles.inputContainer}>
                                <TextInput
                                    style={styles.input}
                                    placeholder="请输入工单号"
                                    placeholderTextColor="#999"
                                    value={workOrderNumber}
                                    onChangeText={setWorkOrderNumber}
                                    onSubmitEditing={handleWorkOrderSubmitEditing}
                                    returnKeyType="search"
                                />
                                {workOrderNumber.length > 0 && (
                                    <TouchableOpacity
                                        style={styles.clearButton}
                                        onPress={() => {
                                            setWorkOrderNumber('');
                                            setMaterialList([]);
                                            setWorkOrderData(null);
                                        }}
                                    >
                                        <Text style={styles.clearButtonText}>×</Text>
                                    </TouchableOpacity>
                                )}
                            </View>
                            <TouchableOpacity
                                style={styles.scanBtn}
                                onPress={handleWorkOrderScan}
                                disabled={loading}
                            >
                                <Image source={saoma} style={{ width: 30, height: 30 }} />
                            </TouchableOpacity>
                        </View>
                    </View>

                    {/* 可领用物料列表 */}
                    {materialList.length > 0 && (
                        <View style={styles.materialListSection}>
                            <Text style={styles.sectionTitle}>可领用物料列表</Text>
                            {materialList.map((material, index) => (
                                <View key={index} style={styles.materialItem}>
                                    <View style={styles.materialDetails}>
                                        <View style={styles.detailRow}>
                                            <Text style={styles.detailLabel}>物料名称:</Text>
                                            <Text style={styles.detailValue}>{material.materialName || material.product_short_name}</Text>
                                        </View>
                                        <View style={styles.detailRow}>
                                            <Text style={styles.detailLabel}>物料编码:</Text>
                                            <Text style={styles.detailValue}>{material.materialEncode || material.product_encode}</Text>
                                        </View>
                                        <View style={styles.detailRow}>
                                            <Text style={styles.detailLabel}>储位:</Text>
                                            <Text style={styles.detailValue}>{material.shelf_num}</Text>
                                        </View>
                                        <View style={styles.detailRow}>
                                            <Text style={styles.detailLabel}>总需求数量:</Text>
                                            <Text style={styles.detailValue}>{material.totalQuantity}</Text>
                                        </View>
                                        <View style={styles.detailRow}>
                                            <Text style={styles.detailLabel}>储位量:</Text>
                                            <Text style={styles.detailValue}>{material.quantity}</Text>
                                        </View>
                                    </View>
                                </View>
                            ))}
                        </View>
                    )}

                    {/* 储位扫描区域 */}
                    <View style={styles.scanSection}>
                        <Text style={styles.sectionTitle}>储位扫描</Text>
                        <View style={styles.inputRow}>
                            <View style={styles.inputContainer}>
                                <TextInput
                                    ref={shelfInputRef}
                                    style={styles.input}
                                    placeholder="请输入储位编号"
                                    placeholderTextColor="#999"
                                    value={shelfNumber}
                                    onChangeText={setShelfNumber}
                                    onSubmitEditing={handleShelfSubmitEditing}
                                    returnKeyType="search"
                                />
                                {shelfNumber.length > 0 && (
                                    <TouchableOpacity
                                        style={styles.clearButton}
                                        onPress={() => {
                                            setShelfNumber('');
                                        }}
                                    >
                                        <Text style={styles.clearButtonText}>×</Text>
                                    </TouchableOpacity>
                                )}
                            </View>
                            <TouchableOpacity
                                style={styles.scanBtn}
                                onPress={handleShelfScan}
                                disabled={loading}
                            >
                                <Image source={saoma} style={{ width: 30, height: 30 }} />
                            </TouchableOpacity>
                        </View>
                    </View>

                    {/* 已选物料列表 */}
                    {selectedMaterials.length > 0 && (
                        <View style={styles.selectedMaterialsSection}>
                            <Text style={styles.sectionTitle}>已选物料列表</Text>
                            {selectedMaterials.map((material, index) => (
                                <View key={index} style={styles.selectedMaterialItem}>
                                    <View style={styles.materialDetails}>
                                        <View style={styles.detailRow}>
                                            <Text style={styles.detailLabel}>物料名称:</Text>
                                            <Text style={styles.detailValue}>{material.product_name}</Text>
                                        </View>
                                        <View style={styles.detailRow}>
                                            <Text style={styles.detailLabel}>物料编码:</Text>
                                            <Text style={styles.detailValue}>{material.product_encode}</Text>
                                        </View>
                                        <View style={styles.detailRow}>
                                            <Text style={styles.detailLabel}>储位:</Text>
                                            <Text style={styles.detailValue}>{material.shelf_num}</Text>
                                        </View>
                                        <View style={styles.detailRow}>
                                            <Text style={styles.detailLabel}>储位数量:</Text>
                                            <Text style={styles.detailValue}>{material.quantity}</Text>
                                        </View>
                                        <View style={styles.detailRow}>
                                            <Text style={styles.detailLabel}>领用数量:</Text>
                                            <TextInput
                                                style={styles.claimQuantityInput}
                                                placeholder="请输入"
                                                placeholderTextColor="#999"
                                                value={material.claimQuantity}
                                                onChangeText={(value) => handleClaimQuantityChange(index, value)}
                                                keyboardType="numeric"
                                            />
                                        </View>
                                        <View style={styles.detailRow}>
                                            <Text style={styles.detailLabel}></Text>
                                            <TouchableOpacity
                                                style={styles.deleteButton}
                                                onPress={() => handleDeleteMaterial(index)}
                                            >
                                                <Text style={styles.deleteButtonText}>删除</Text>
                                            </TouchableOpacity>
                                        </View>
                                    </View>
                                </View>
                            ))}
                        </View>
                    )}

                    {/* 工单扫码模态框 */}
                    <Modal visible={workOrderScanVisible} animationType="slide">
                        <CustomQRScanner
                            onRead={handleWorkOrderScanResult}
                            onClose={() => setWorkOrderScanVisible(false)}
                        />
                    </Modal>

                    {/* 储位扫码模态框 */}
                    <Modal visible={shelfScanVisible} animationType="slide">
                        <CustomQRScanner
                            onRead={handleShelfScanResult}
                            onClose={() => setShelfScanVisible(false)}
                        />
                    </Modal>

                    {/* 加载状态 */}
                    {loading && (
                        <View style={styles.loadingContainer}>
                            <Text style={styles.loadingText}>处理中...</Text>
                        </View>
                    )}
                </ScrollView>

                {/* 领料按钮 - 固定在底部，不参与滚动 */}
                {selectedMaterials.length > 0 && (
                    <TouchableOpacity
                        style={[styles.claimButton, loading && styles.claimButtonDisabled]}
                        onPress={handleClaimSubmit}
                        disabled={loading}
                    >
                        <Text style={styles.claimButtonText}>领料</Text>
                    </TouchableOpacity>
                )}
            </View>
        </SafeAreaView>
    );
};

export default Picking; 